//
//  LMTabBar.m
//  李明微博
//
//  Created by apple on 15/12/3.
//  Copyright (c) 2015年 李明. All rights reserved.
//

#import "LMTabBar.h"
#import "LMTabBarButton.h"

@interface LMTabBar()

@property(nonatomic,weak)UIButton *plusBtn;

@property(nonatomic,strong)NSMutableArray *buttons;

@property(nonatomic,weak)UIButton *selecedButton;
@end

@implementation LMTabBar

-(NSMutableArray *)buttons
{
    if (_buttons ==nil) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}

- (void)setItems:(NSArray *)items
{
    _items = items;
    
    for (UITabBarItem *item in items) {
        
        LMTabBarButton *btn = [LMTabBarButton buttonWithType:UIButtonTypeCustom];
        
        btn.item = item;
        
        btn.tag = self.buttons.count;
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
        
        if (btn.tag ==0) {
            [self btnClick:btn];
        }
        
        [self addSubview:btn];
        [self.buttons addObject:btn];
    }
    
    
}

- (void)btnClick:(UIButton *)button
{
    _selecedButton.selected = NO;
    button.selected = YES;
    _selecedButton = button;
    
    if ([_delegate respondsToSelector:@selector(tabBar:didClickButton:)]) {
        [_delegate tabBar:self didClickButton:button.tag];
    }
}

-(UIButton *)plusBtn
{
    if (_plusBtn==nil) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [btn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        
        [btn setImage:[UIImage imageNamed:@"tabbar_compose_background_icon_add"] forState:UIControlStateHighlighted];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        
        _plusBtn = btn;
        
        [btn sizeToFit];
        
        [self addSubview:_plusBtn];
    }
    return _plusBtn;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    
    
    
    CGFloat w = self.width ;
    CGFloat h = self.height;
    
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    
    /*
     self.items.count+1 目前只有4个需要＋1个方便以后加入
     */
    CGFloat btnW = w / (self.items.count+1);
    CGFloat btnH = h;
    
    
    int i = 0;
    for (UIView *tabBarBtn in self.subviews) {
        
        if ([tabBarBtn isKindOfClass:NSClassFromString(@"LMTabBarButton")]) {
            
            if(i==2)
            {
                i=3;
            }
            
            btnX = i * btnW;
            
            tabBarBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
            
            
            i++;
            
        }
        
    }
    
    self.plusBtn.center = CGPointMake(w*0.5,h*0.5);
    
    
    
}

@end
